<script setup>
import { useRouter, useRoute } from 'vue-router'
import CommunityIcon from '../../components/icons/IconCommunity.vue'
import request from '../../utils/request'
import { ref,defineEmits,defineProps } from 'vue';
import { Toast } from 'vant';
const router = useRouter()
const route = useRoute()

// 当前是否登录
const islogin = ref(true)
// 登录loading
const isloginbut = ref(false)
const disabled = ref(false)
const codeMsg = ref('获取验证码')
const codeNum = ref(60)
const p_code = ref('')
const iframepath = ref('')//嵌入地址
const isagreement = ref(false)//用户协议弹出层
const isagreementtitle = ref('')//弹出标题

// 子组件传递父组件
const emit = defineEmits(['showlogin','loginok'])
const props = defineProps({updatedLogin:Boolean,codeData:String})
islogin.value = props.updatedLogin
console.log(islogin.value)
p_code.value = props.codeData
// 登录用户信息
const userdata = ref({})

// 用户初始状态
const logininfo = ref({
    phone: "",
    code: "",
    checked: ''
})
const userTel = ref([
    {
        required: true,
        message: "请输入手机号",
        trigger: "onBlur"
    },
    {
        validator: value => {
            return /^1[23456789]\d{9}$/.test(value);
        },
        message: "请输入正确格式的手机号"
    }])
//关闭登录弹窗
function close() {
    islogin.value = false
    // 子组件传递父组件
    emit('showlogin',false)
}
function agreement(item, title) {
    iframepath.value = item
    isagreementtitle.value = title
    isagreement.value = true
}
//获取验证码
function sendCode() {

    // 验证手机号格式是否正确
    if (!userTel.value[1].validator(logininfo.value.phone)) {
        Toast.fail('请先输入正确的手机号');
        return
    }
    let data = {
        mobile: logininfo.value.phone,
        p_code: p_code.value
    }
    request({
        url: '/api/user/sendCode',
        method: 'post',
        data
    }).then(res => {
        if (res.data.status == 200) {
            console.log('验证码发送成功')
            // 禁用按钮
            disabled.value = true;
            // 倒计时
            let timer = setInterval(() => {
                --codeNum.value;
                codeMsg.value = `验证码(${codeNum.value})`;
            }, 1000);
            // 判断什么时候停止定时器
            setInterval(() => {
                clearInterval(timer);
                codeNum.value = 60;
                disabled.value = false;
                codeMsg.value = "获取短信验证码";
            }, 60000);
        } else {
          Toast.fail(res.data.message);
        }
    })

}
// 登录
function onsubmit() {

    // 判断隐私协议是否勾选

    if (logininfo.value.checked == false || logininfo.value.checked == '') {
        Toast.fail('请先详细阅读并同意用户协议与隐私政策');
        return
    } else if (logininfo.value.phone == '') {
        Toast.fail('请先输入正确的手机号');
        return
    } else if (logininfo.value.code == '') {
        Toast.fail('请先输入正确的验证码');
        return
    } else {
        isloginbut.value = true
        // 进入登录操作
        let data = {
            mobile: logininfo.value.phone,
            mobile_code: logininfo.value.code,
            p_code: p_code.value
        }
        request({
          url:'/api/user/login',
          method:'post',
          data
        }).then(res =>{
          if (res.data.status == 200) {
            userdata.value = res.data.data
            // 存储用户信息
            localStorage.setItem('userdata', JSON.stringify(res.data.data))
            isloginbut.value = false
            islogin.value = false
            emit('loginok',true)
            // 子组件传递父组件
            emit('showlogin',false)
          }else{
            isloginbut.value = false
            Toast.fail(res.data.message);
          }
        })
    }
}
</script>

<template>
    <van-overlay :show="islogin" class="loginstyle">
        <div class="flex justify-center items-center h-full flex-col">
            <div class="w-[90%] flex justify-end md:pr-[10rem]  ">
                <CommunityIcon @click="close"></CommunityIcon>
                <!-- <img src="../assets/img/gb.png" class="w-[1.5rem] max-w-[1.5rem]  mb-1" alt="关闭" @click="isform = false"> -->
            </div>
            <div class="w-[90%] h-[20rem] max-w-[400px] bg-[#fff] rounded-lg flex justify-center  flex-col">
                <div class=" flex justify-center font-bold"> 短信验证码登录</div>
                <div class=" flex justify-center">
                    <div class="w-[85%]">
                        <van-form ref="form" class="mt-[1rem]">
                            <van-field v-model="logininfo.phone" autocomplete="off" type="tel" maxlength="11" clearable
                                name="tel" :rules="userTel" placeholder="请输入手机号" />
                            <van-field v-model="logininfo.code" autocomplete="off" maxlength="6" center clearable
                                placeholder="短信验证码" :rules="[{ required: true, message: '请填写验证码' }]" type="digit">
                                <template #button>
                                    <van-button round type="success" style="height:2.5rem; width:7rem;" size="small"
                                        @click="sendCode" :disabled="disabled" color="rgb(246,120,72)" native-type="button">
                                        {{ codeMsg }}
                                    </van-button>
                                </template>
                            </van-field>
                            <div class="mx-[0.426rem] mt-[1rem] flex justify-center">
                                <van-button style="width:13rem;height: 2.5rem; " :loading="isloginbut" round type="success"
                                    size="large" color="rgb(246,120,72)" @click="onsubmit()">立即登录
                                </van-button>
                            </div>
                            <div class=" h-full mx-[1rem] flex justify-center">
                                <van-field name="radio" label="" whidth="1rem"
                                    :rules="[{ required: true, message: '请填写验证码' }]">
                                    <template #input class=" h-full flex justify-center">
                                        <van-checkbox v-model="logininfo.checked" class="" checked-color="rgb(246,120,72)">
                                        </van-checkbox>
                                        <div class="ml-2 text-[0.8rem]">
                                            我已同意<span
                                                @click="agreement('https://sdk.nextjoy.com/init/init/getRegster?gid=34', '用户协议')"
                                                class=" decoration-1 text-[rgb(246,120,72)]">用户协议</span>与<span
                                                @click="agreement('https://sdk.nextjoy.com/init/init/getPrivacy?gid=34', '隐私协议')"
                                                class=" decoration-1 text-[rgb(246,120,72)]">隐私协议</span>
                                        </div>
                                    </template>
                                </van-field>
                            </div>
                        </van-form>
                    </div>

                </div>
            </div>
        </div>
    </van-overlay>
    <van-dialog width="90%" styel="height:800px;" :showCancelButton=false v-model:show="isagreement">
        <iframe class="w-full h-[370px]" :src="iframepath" frameborder="0"></iframe>
    </van-dialog>
</template>
<style scoped>
.loginstyle {
    z-index: 100 !important;
}
</style>